%Goal: Warehouse lending market equilibrium

%INPUTS:
%alpha: household price sensitivity
%F: total mortgage face value
%Nb: number of local banks
%No: number of non-local banks
%Nn: number of shadow banks
%qn: shadow bank mortgage quality 
%qb: bank mortgage quality
%rho0: bank funding cost
%rhon: common component of shadow bank funding cost
%eta: warehouse duration
%sigma_xi: volatility of shadow bank idiosyncratic taste shock
%co: non-local bank marginal cost of warehouse lending
%cb: local bank marginal cost of warehouse lending
%shadow bank idiosyncratic taste shock

% Local bank Optimization problem


function [rno,sno,rnb,snb,rm,sbm,rb,sb, rhob, sbw, sow, markup1, markup2] = Solve_local(F,sigma,psim,psiw,alpha,k,Nb,Nn,Nm,qn,qb,eta,rhoo)
MaxIterations=10000;
tol = 10^(-6);
sbw_initial = 0.029;
sbw = [];
rhob_initial = 4.03;
delta =0.1;
rhob = [];
diff = 1000;
iter = 0;

while diff>tol && iter<=MaxIterations  
    iter = iter+1;
    % Given sbw_initial, first find rhob;
    diff2 = 1000;
    iter2 = 0;
    while diff2>tol && iter<=MaxIterations
        iter2 = iter2+1;
        sow = 1-sbw_initial*Nb; % residual market share
        [rno,sno,rnb,snb,rm,sbm,rb,sb] = Solve_wbank(psim,psiw,alpha,k,Nb,Nn,Nm,qn,qb,eta,rhoo,rhob_initial,sow,sbw_initial);
        sbw = (snb*F/(alpha*(1-snb)))^sigma/((sno*F/(alpha*(1-sno)))^sigma+Nb*(snb*F/(alpha*(1-snb)))^sigma);
        diff2 = abs(sbw-sbw_initial);
        sbw_initial = sbw;
    end
        % Given sbw_initial and rhob_initial, approximate dsnb/drhob, drb/drhob, dsb/drhob; 
    sow = 1-sbw*Nb; % residual market share
    rhobl = rhob_initial+delta;
        % find drb dsb
        % and dsnb using Solve_profit_bank2
    
    [~, ~, ~,snbl1,~,~,~,~,rbl1,sbl1,~,~] = Solve_profit_wbank_other(psim,psiw,alpha,k,Nb,Nn,Nm,qn,qb,eta,rhoo,rhob_initial,rhob_initial,sow,sbw);
    [~, ~, ~,snbl2,~,~,~,~,rbl2,sbl2,~,~] = Solve_profit_wbank_other(psim,psiw,alpha,k,Nb,Nn,Nm,qn,qb,eta,rhoo,rhob_initial,rhobl,sow,sbw);
               
    drb = (rbl2-rbl1)/delta;
    dsb = (sbl2-sbl1)/delta;
    dsnb = (snbl2-snbl1)/delta;
    
    rhob = psiw+snbl1/(-dsnb*(1+sigma*(1-sbw)/(snbl1*(1-snbl1))))+(drb*sbl1+(rbl1-psim)*dsb)*(eta*Nn*sbw*(-dsnb*(1+sigma*(1-sbw)/(snbl1*(1-snbl1)))))^(-1);
    markup1 = snbl1/(-dsnb*(1+sigma*(1-sbw)/(snbl1*(1-snbl1))));
    markup2 = (drb*sbl1+(rbl1-psim)*dsb)*(eta*Nn*sbw*(-dsnb*(1+sigma*(1-sbw)/(snbl1*(1-snbl1)))))^(-1);
    diff = abs(rhob-rhob_initial);
    rhob_initial = rhob;
end
sbw = (snb*F/(alpha*(1-snb)))^sigma/((sno*F/(alpha*(1-sno)))^sigma+Nb*(snb*F/(alpha*(1-snb)))^sigma);
sow = 1-sbw*Nb; % residual market share
[rno,sno,rnb,snb,rm,sbm,rb,sb] = Solve_wbank(psim,psiw,alpha,k,Nb,Nn,Nm,qn,qb,eta,rhoo,rhob,sow,sbw);
end